<?php
namespace App\Services;

use App\Models\TourOrderRefund;
use App\Models\TourOrderRefundLog;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use League\Flysystem\Exception;

/**
 *
 * 路线退款款服务层
 *
 * @author shengl@maqu.im
 *
 */
class TourRefundService extends BaseService {

    public function applyRefundTourOrder($user_id,$id,$reason,$tuan_status,$withTrans = true){

        //买家用户信息
        $userInfo = User::find($user_id);

        $tourOrderService = new TourOrderService();
        //获取订单信息
        $tourOrderInfoData = $tourOrderService->getOrderInfo($user_id,$id);

        if(!$tourOrderInfoData['result']){
            return $this->failure($tourOrderInfoData['msg']);
        }

        $tourOrderInfo = $tourOrderInfoData['data'];

        if($tourOrderInfo->buyer_id != $user_id ){
            return $this->failure('无权操作该订单');
        }

        if($tourOrderInfo->status == TOUR_ORDER_PENDING){
            return $this->failure('该订单尚未支付');
        }elseif($tourOrderInfo->status != TOUR_ORDER_ACCEPTED && $tourOrderInfo->status != TOUR_ORDER_SUBMITTED ){
            return $this->failure('该旅行订单已出行或者已经申请退款，不可重复申请退款');
        }
        if($tourOrderInfo->tourOrderRefund){
            if($tourOrderInfo->tourOrderRefund->refund_status == TOUR_REFUND_PENDING || $tourOrderInfo->tourOrderRefund->refund_status == TOUR_REFUND_REFUNDING){
                return $this->failure('已经申请退款,请勿重复申请，可询问客服查询进度');
            }
        }

        //配置项
        $configs = app('maqu.config')->getAllConfigs();
        $tour_refund_singlebuy = $configs[CONFIG_CODE_tour_refund_singlebuy];
        $tour_refund_groupbuy_before = $configs[CONFIG_CODE_tour_refund_groupbuy_before];
        $tour_refund_groupbuy_after = $configs[CONFIG_CODE_tour_refund_groupbuy_after];
        $tour_refund_deadline = $configs[CONFIG_CODE_tour_refund_deadline];

        $rest_time = $tourOrderInfo->tourOrderTour->open_date-gmtime();
        $rest_date = $rest_time/86400;
        if($rest_date < $tour_refund_deadline){
            return $this->failure('该订单即将出行，已不可退款');
        }

        $tour_refund_percent = 0;
        switch($tourOrderInfo->extension){
            case 'normal':
                $tour_refund_percent = $tour_refund_singlebuy;
                break;
            case 'groupbuy':
                if($tuan_status!= $tourOrderInfo->tourTuan->state){
                    return $this->failure('该团状态已变更，为了避免你的损失请刷新后再申请');
                }
                if($tourOrderInfo->tourTuan->state == TUAN_STATE_WAITE){
                    $tour_refund_percent = $tour_refund_groupbuy_before;
                }elseif($tourOrderInfo->tourTuan->state == TUAN_STATE_SUCCESS){
                    $tour_refund_percent = $tour_refund_groupbuy_after;
                }
                break;
            default:;
        }

        $refund_fee = $tourOrderInfo->order_amount * (100 - $tour_refund_percent)/100;

        if($withTrans){
            DB::beginTransaction();
        }
        try {
            switch($tourOrderInfo->extension){
                case 'normal':  //单买
                    $new_order_status = $tourOrderInfo->status = TOUR_ORDER_REFUNDING;//进入申请流程
                    $refund_status = TOUR_REFUND_PENDING;
                    break;
                case 'groupbuy':    //拼团

                    if($tourOrderInfo->tourTuan->state == TUAN_STATE_WAITE){    //组团中
                        $new_order_status = $tourOrderInfo->status = TOUR_ORDER_AGREE;//未成团直接跳过审核流程 进入退款
                        $refund_status = TOUR_REFUND_REFUNDING;
                        //取得所购买的人数
                        $quantity = DB::table('tour_tuan_data')
                               ->where('order_id',$tourOrderInfo->order_id)
                               ->value('quantity');
                        //释放所占团份数 份数
                        DB::table('tour_tuan')
                            ->where('tuan_id',$tourOrderInfo->tourTuan->tuan_id)
                            ->increment('rest_copies',$quantity);

                        DB::table('tour_tuan_data')
                            ->where('order_id',$tourOrderInfo->order_id)
                            ->update([
                                'state' => TUAN_DATA_STATE_FAILURE,//把团支付状态改为退款（2）
                            ]);
                    } else if($tourOrderInfo->tourTuan->state == TUAN_STATE_SUCCESS){ //成团
                        $new_order_status = $tourOrderInfo->status = TOUR_ORDER_REFUNDING;
                        $refund_status = TOUR_REFUND_PENDING;
                    } else {
                        throw new Exception('logic error');
                    }

                    break;
            }

            $tourOrderInfo->save();

            $old_status = $tourOrderService->tourOrderStatus(TOUR_ORDER_ACCEPTED);
            $new_status = $tourOrderService->tourOrderStatus($new_order_status);
            $tourOrderService->addTourOrderLog($tourOrderInfo->order_id,$userInfo->nickname,$old_status,$new_status,'用户申请退款',false);

            $tourOrderRefund = TourOrderRefund::where('order_id',$tourOrderInfo->order_id)->first();

            if(!$tourOrderRefund){
                $tourOrderRefund = new TourOrderRefund();
            }

            $tourOrderRefund->order_id = $tourOrderInfo->order_id;
            $tourOrderRefund->applier = $user_id;
            $tourOrderRefund->apply_date = gmtime();
            $tourOrderRefund->apply_reason = $reason;
            $tourOrderRefund->refund_status = $refund_status;
            $tourOrderRefund->refund_fee = $refund_fee;
            $tourOrderRefund->last_time = 0;
            $tourOrderRefund->save();

            self::addOrderRefundLog($tourOrderRefund->refund_id,$userInfo->nickname,'用户申请退款','用户申请退款',false);

            DB::table('tour_order')
                ->where('order_id',$id)
                ->update([
                    'status' => $new_order_status,//如果是单买订单或者是已成团的订单 进入申请流程 退款中（21）
                ]);

            /* 操作记录 */
            $order_log = [
                'order_id'  => $id,
                'operator'  => $user_id,
                'order_status' => '待出行',
                'changed_status' =>'退款中' ,
                'remark'    => '用户申请退款',
                'log_time'  => gmtime(),
            ];

            DB::table('tour_order_log')->insert($order_log);

            if($withTrans){
                DB::commit();
            }
            return $this->success();

        } catch (\Exception $e) {
            if($withTrans){
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
            return $this->failure('处理错误，暂时无法申请退款');
        }
    }

    /**
     *    获取订单状态相应的文字表述
     *
     *    @param     int $refund_type  退款类型 1->退款 2->退货 0->无
     *    @param     int $refund_status  退款/货状态
     *    @return    string
     */
    public function refundStatus($refund_status=0)
    {
        $lang_key = '';
        switch ($refund_status)
        {
            case TOUR_REFUND_PENDING://等待卖家同意退款
                $lang_key = 'refund_pending';
                break;
            case TOUR_REFUND_REFUSED://已拒绝
                $lang_key = 'refund_refused';
                break;
            case TOUR_REFUND_REFUNDING:// 退款中
                $lang_key = 'refund_refunding';
                break;
            case TOUR_REFUND_FINISHED:// 退款成功
                $lang_key = 'refund_finished';
                break;
            case TOUR_REFUND_CANCELED:// 退款已取消
                $lang_key = 'refund_canceled';
                break;
        }

        $keyvalues = array(
            'refund_pending'   => '退款待审核',
            'refund_refused'   => '退款申请被拒绝',
            'refund_refunding'   => '退款中',
            'refund_finished'	=> '退款成功',
            'refund_canceled'    => '退款已取消');

        return $lang_key  ? $keyvalues[$lang_key] : $lang_key;
    }

    /**添加路线退款单日志
     * @param $refund_id
     * @param $user_name
     * @param $old_status
     * @param $new_status
     * @param $remark
     * @param bool|false $withTrans
     */
    public function addOrderRefundLog($refund_id,$user_name,$old_status,$new_status,$remark,$withTrans = false){
        if($withTrans){
            DB::beginTransaction();
        }
        try{
            $tourOrderRefundLog = new TourOrderRefundLog();
            $tourOrderRefundLog->refund_id = $refund_id;
            $tourOrderRefundLog->operator = addslashes($user_name);
            $tourOrderRefundLog->refund_status = $old_status;
            $tourOrderRefundLog->changed_status = $new_status;
            $tourOrderRefundLog->remark = $remark;
            $tourOrderRefundLog->log_time = gmtime();

            $tourOrderRefundLog->save();
            if($withTrans){
                DB::commit();
            }
        }catch (\Exception $e){
            Log::ERROR($e->getMessage());
            if($withTrans){
                DB::rollback();
            }
        }
    }

}
